package com.lei.app.websocket;

/**
 * Created by IntelliJ IDEA.
 * User: 306955302@qq.com
 * Date: 2016/9/13 0013
 * To change this template use File | Settings | File Templates.
 */

import org.nutz.ioc.Ioc;
import org.nutz.mvc.Mvcs;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;

/***
 * 配置
 * @author zxq(956607644@qq.com)  
 * @date 2020/4/9 9:47

 * @return   
 */  
public class NutIocWebSocketConfigurator extends ServerEndpointConfig.Configurator {

    @Override
    public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
        Ioc ioc = Mvcs.getIoc();
        if (ioc == null) {
            ioc = Mvcs.ctx().getDefaultIoc();
        }
        return ioc.get(endpointClass);
    }

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        super.modifyHandshake(sec, request, response);
        // 如果是Nutz MVC环境, 从mvc上下文直接获取Request对象
        HttpServletRequest req = Mvcs.getReq();
        if (req != null) {
            sec.getUserProperties().put(HttpSession.class.getName(), req.getSession(false));
            return;
        }
        javax.servlet.http.HttpSession session = (javax.servlet.http.HttpSession) request.getHttpSession();
        if (session != null) {
            sec.getUserProperties().put(HttpSession.class.getName(), session);
        }
    }
}
